#include <GL/glut.h>
#include <iostream>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include "../draw.h"
#include "screens.h"
#include "externs.h"
#include "../../model/elements/scene/Textures.h"
#include "../../tinyxml/tinyxml.h"

using namespace std;


OpeningScreen::OpeningScreen(string mapDir)
{
	getMaps(mapDir);

	fileStart=-4;
	fileEnd=5;

	Button *tmp=new Button(50,25,160,75,"PLAY",0);
	tmp->setFg(0,1,0);
	tmp->setBg(1,1,1);
	buttons.push_back(*tmp);
	delete tmp;

	tmp=new Button(190,25,300,75,"QUIT",0);
	tmp->setFg(1,0,0);
	tmp->setBg(1,1,1);
	buttons.push_back(*tmp);
	delete tmp;

	tmp=new Button(400,25,560,75,"NEW LEVEL",0);
	buttons.push_back(*tmp);
	delete tmp;

	tmp=new Button(590,25,750,75,"EDIT LEVEL",0);
	buttons.push_back(*tmp);
	delete tmp;

	tmp=new Button(309,330,327,350,"UP",0);
	tmp->setBg(0.4,0.4,0.4);
	buttons.push_back(*tmp);
	delete tmp;

	tmp=new Button(309,300,327,320,"DOWN",0);
	tmp->setBg(0.4,0.4,0.4);
	buttons.push_back(*tmp);
	delete tmp;

}

void OpeningScreen::init()
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0,WIDTH,0,HEIGHT,-10,10);
	getMaps("./maps");
	fileStart=-4;
	fileEnd=5;
	glutPostRedisplay();
}

void OpeningScreen::getMaps(string dir)
{
	DIR *pDIR;
	struct dirent *pDirEnt;
	TiXmlElement* pChild;

	/* Open the current directory */
	pDIR = opendir(dir.c_str());

	if(pDIR==NULL)
		cerr << dir << " directory does not exist" << endl;

	/* Get each directory entry from pDIR and print its name */
	maps.clear();
	mapNames.clear();
	mapDescriptions.clear();

	pDirEnt=readdir(pDIR);
	while ( pDirEnt != NULL ) {
		if(strcmp(".",pDirEnt->d_name) && strcmp("..",pDirEnt->d_name))
		{
			string tmpPath(pDirEnt->d_name);
			tmpPath="./maps/"+tmpPath;
			TiXmlDocument doc(tmpPath.c_str());
			bool loadOkay = doc.LoadFile();
			if (loadOkay)
			{
				maps.push_back(pDirEnt->d_name);
				for ( pChild = doc.RootElement()->FirstChildElement(); pChild != 0; pChild = pChild->NextSiblingElement())
				{
					if(!strcmp(pChild->Value(),"previewFilePath"))
					{
						if(pChild->GetText())
						{
							cout << pChild->GetText() << endl;
							mapPreviewFilePaths.push_back(pChild->GetText());
						}
						else
						{
							mapPreviewFilePaths.push_back("data/thumbnails/NONE.BMP");
						}

						Textures::pushPreview(mapPreviewFilePaths[mapPreviewFilePaths.size()-1]);
					}
					if(!strcmp(pChild->Value(),"name"))
					{
						if(pChild->GetText())
						{
							cout << pChild->GetText() << endl;
							mapNames.push_back(pChild->GetText());
						}
						else
						{
							mapNames.push_back("");
						}
					}
					if(!strcmp(pChild->Value(),"description"))
					{
						if(pChild->GetText())
						{
							cout << pChild->GetText() << endl;
							cout << "========" << endl;
							mapDescriptions.push_back(pChild->GetText());
						}
						else
							mapDescriptions.push_back("");
					}
				}

			}
			else
			{
				printf("Failed to load file \"%s\"\n", pDirEnt->d_name);
			}

			//Read map Name and description from file

		}
		pDirEnt=readdir(pDIR);
	}

	/* Release the open directory */

	closedir( pDIR );

}

void OpeningScreen::display(void)
{
	glClearColor(0.01,0.01,0.02,0);
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	glColor3d(1,1,1);
	Draw::Text(75,570,"Map List:",-1,SMALLER);
	Draw::Text(475,525,"Image of Selected Map:",-1,SMALLER);


	if(fileStart+4<(int)mapPreviewFilePaths.size() && fileStart+4>=0)
	{
		//fileStart+4. icin preview ciz eger yoksa cizme!
		if(mapPreviewFilePaths[fileStart+4]=="")
			Draw::FramedRectangle(450,250,700,500);
		else
		{
			cout << "Texture kaplayacagim " << fileStart+4 << " "<< Textures::previewImageIds[fileStart+4] << endl;
			glEnable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, Textures::previewImageIds[fileStart+4]);

			glBegin(GL_QUADS);
			{
				glTexCoord2d(0,0); glVertex2d(450,250);
				glTexCoord2d(0,1); glVertex2d(450,500);
				glTexCoord2d(1,1); glVertex2d(700,500);
				glTexCoord2d(1,0); glVertex2d(700,250);
			}
			glEnd();
			glDisable(GL_TEXTURE_2D);

		}
	}
	else
		Draw::FramedRectangle(450,250,700,500);

	Draw::FramedRectangle(400,100,750,225);
	Draw::FramedRectangle(49,101,299,551);
	glColor3f(0.2,0.2,0.2);
	Draw::Rectangle(50,500,300,550);
	Draw::Rectangle(50,100,300,150);
	glColor3f(0.3,0.3,0.3);
	Draw::Rectangle(50,450,300,500);
	Draw::Rectangle(50,150,300,200);
	glColor3f(0.4,0.4,0.4);
	Draw::Rectangle(50,400,300,450);
	Draw::Rectangle(50,200,300,250);
	glColor3f(0.5,0.5,0.5);
	Draw::Rectangle(50,350,300,400);
	Draw::Rectangle(50,250,300,300);
	glColor3f(1,1,1);
	Draw::Rectangle(50,300,300,350);

	Draw::Triangle(306,330,330,330,318,355);
	Draw::Triangle(306,320,330,320,318,295);


	glColor3f(0.01,0.01,0.02);
	if(fileStart+4<(int)mapDescriptions.size() && fileStart+4>=0)
		Draw::Text(425,200,mapDescriptions[fileStart+4],-1,SMALLER);
	else
		Draw::Text(425,200,"Map Description",-1,SMALLER);


	// -2 FOR ARROWS TO NOT DRAW
	for(unsigned int i=0;i<buttons.size()-2;i++)
		buttons[i].draw();

	glColor3f(0,0,0);
	for(int i=fileStart,j=0;i<fileEnd;i++,j++)
	{
		if(i>-1 && i<(int)mapNames.size())
			Draw::Text(60,525-j*50,mapNames[i],-1,SMALL);
	}

  	glutSwapBuffers();
}

void OpeningScreen::keyboard(unsigned char key,int x, int y)
{
	if(key==GLUT_KEY_DOWN)
	{
		if(fileStart==(int)(maps.size())-5)
			return;
		fileStart++;
		fileEnd++;
		glutPostRedisplay();
	}
	else if(key==GLUT_KEY_UP)
	{
		if(fileStart==-4)
			return;
		fileStart--;
		fileEnd--;
		glutPostRedisplay();
	}
}

void OpeningScreen::special(int key,int x, int y)
{

}

void OpeningScreen::specialUp(int key,int x, int y)
{

}

void OpeningScreen::keyboardUp(unsigned char key,int x, int y)
{

}
void OpeningScreen::mouse(int button, int state,int x, int y_)
{
	int y=HEIGHT-y_;
	if(state==GLUT_DOWN && button==GLUT_LEFT_BUTTON)
	{
		if(buttons[PLAY].isClicked(x,y))
		{
			turn->resetPlayerId(); //TODO Game Logic eklenince duzeltmen gerekecek gibi
			gameplay->setEnvironment(maps[fileStart+4]);
			screenMode=TURN;
			glutPostRedisplay();
		}
		else if(buttons[QUIT].isClicked(x,y))
			exit(0);
		else if(buttons[EDIT_LEVEL].isClicked(x,y))
		{
			screenMode=EDITOR;
			editor->setEnvironment(EDIT,maps[fileStart+4]);

			glutPostRedisplay();
		}
		else if(buttons[NEW_LEVEL].isClicked(x,y))
		{
			screenMode=EDITOR;
			editor->setEnvironment(NEW,"");
			glutPostRedisplay();
		}
		else if(buttons[UP].isClicked(x,y))
		{
			if(fileStart==-4)
				return;
			fileStart--;
			fileEnd--;
			glutPostRedisplay();
		}
		else if(buttons[DOWN].isClicked(x,y))
		{
			if(fileStart==(int)(maps.size())-5)
				return;
			fileStart++;
			fileEnd++;
			glutPostRedisplay();
		}
	}
}

void OpeningScreen::motion(int x, int y_)
{

}
void OpeningScreen::passiveMotion(int x, int y_)
{
/*	int y=HEIGHT-y_;
	if(buttons[PLAY].isClicked(x,y))
	{
		cout << "motiona girdim" <<endl;

		buttons[PLAY].MouseOverHighlight();
		glutPostRedisplay();

	}*/
}
